#!/bin/sh
#Created by Wenl
#Set the number of the maximum downloading tasks
MAXDONLOADING="1"
#Set the number of the maximum seeding tasks
MAXSEEDING="10"
#Set the command
COMMAND="transmission-remote 127.0.0.1:9091 --auth=root:toor"

if [ $(ps|grep DvdPlayer|wc -l) -gt 31 ]; then
 exit
fi

#Launch transmission if it's down
if [ $(ps|grep transmission-daemon|wc -l) -le 1 ]; then
  /opt/etc/init.d/S50transmission
  sleep 1
fi

if [ $(ps|grep transmission-daemon|wc -l) -le 1 ]; then
 exit
fi

#Limit the seeding tasks to the setting
N=`expr $($COMMAND -l | grep 100%|grep -v Stopped| wc -l) - $MAXSEEDING`

if [ $N -gt 0 ]; then
  LIST="$($COMMAND -l | grep 100%|grep -v Stopped| head -n $N|gawk '{ print $1; }')"
  for ID in $LIST; do
    $COMMAND --torrent $ID --stop > /dev/null   
    sleep 2
  done
fi

N=`expr $MAXSEEDING - $($COMMAND -l | grep 100%|grep -v Stopped| wc -l)`
if [ $N -gt 0 ]; then
  LIST="$($COMMAND -l | grep 100%|grep Stopped|head -n $N|gawk '{ print $1; }')"
  for ID in $LIST; do
    $COMMAND --torrent $ID --start > /dev/null
    sleep 3
  done
fi

N=`expr $($COMMAND -l|grep -v Stopped|grep -v 100%|grep -v ID|grep -v Sum|wc -l) - $MAXDONLOADING`
if [ $N -gt 0 ]; then  
  LIST="$($COMMAND -l |grep -v Stopped|grep -v 100%|grep -v ID|grep -v Sum|tail -n $N|gawk '{ print $1; }')"  
  for ID in $LIST; do 
    $COMMAND --torrent $ID --stop > /dev/null 
    sleep 3
  done
fi

if [ $N -lt 0 ]; then
  N=`expr 0 - $N`
  if [ $($COMMAND -l|grep Stopped|grep -v 100%|grep -v ID|wc -l) -gt 0 ]; then     
    LIST="$($COMMAND -l|grep Stopped|grep -v 100%|grep -v ID|head -n $N|gawk '{ print $1; }')" 
    for ID in $LIST; do 
      $COMMAND --torrent $ID --start > /dev/null         
      sleep 3
    done
  fi
fi   
